/*
WLVGoogleImageSelector - Google Picasa Web Plugin for Windows Live Writer
Copyright (C) 2007 Timothy Parez

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using WindowsLive.Writer.Api;
using System.Diagnostics;

namespace Arendee.WindowsLiveWriter.Plugins
{
    public struct ImageSize
    {
        public int Size;
        public string Description;

        public ImageSize(int NSize, string NDescription)
        {
            this.Size = NSize;
            this.Description = NDescription;
        }

        public override string ToString()
        {
            return this.Description;
        }
    }

    public partial class GoogleImageSelectorEditor : SmartContentEditor
    {
        IProperties globalOptions;
        List<ContentSettings> ContentSettingsList = new List<ContentSettings>();

        private int SelectedContentId
        {
            get
            {
                int contentId = this.SelectedContent.Properties.GetInt("contentId", -1);
                if (contentId == -1)
                {
                    contentId = this.ContentSettingsList.Count;
                    this.SelectedContentId = contentId; //Save it
                }

                return contentId;
            }
            set
            {
                this.SelectedContent.Properties.SetInt("contentId", value);
            }
        }

        public GoogleImageSelectorEditor(IProperties GlobalOptions)
        {
            InitializeComponent();
            this.globalOptions = GlobalOptions;
            Application.ThreadException += delegate(object sender, System.Threading.ThreadExceptionEventArgs e) 
            {
                MessageBox.Show(e.Exception.Message + "\n" + e.Exception.InnerException.Message);
            };
        }

        private void GoogleImageSelectorEditor_Load(object sender, EventArgs e)
        {            
            this.cmbImageSize.Items.Add(new ImageSize(32, "32px - Cropped"));
            this.cmbImageSize.Items.Add(new ImageSize(48, "48px - Cropped"));
            this.cmbImageSize.Items.Add(new ImageSize(64, "64px - Cropped"));
            this.cmbImageSize.Items.Add(new ImageSize(72, "72px - Full"));
            this.cmbImageSize.Items.Add(new ImageSize(144, "144px - Full"));
            this.cmbImageSize.Items.Add(new ImageSize(160, "160px - Cropped"));
            this.cmbImageSize.Items.Add(new ImageSize(200, "200px - Full"));
            this.cmbImageSize.Items.Add(new ImageSize(288, "288px - Full"));
            this.cmbImageSize.Items.Add(new ImageSize(320, "320px - Full"));
            this.cmbImageSize.Items.Add(new ImageSize(400, "400px - Full"));
            this.cmbImageSize.Items.Add(new ImageSize(512, "512px - Full"));
            this.cmbImageSize.Items.Add(new ImageSize(576, "576px - Full"));
            this.cmbImageSize.Items.Add(new ImageSize(640, "640px - Full"));
            this.cmbImageSize.Items.Add(new ImageSize(720, "720px - Full"));
            this.cmbImageSize.Items.Add(new ImageSize(800, "800px - Full"));
            this.cmbImageSize.SelectedIndex = 9;
            this.lblVersion.Text = Application.ProductVersion;
        }

        protected override void OnSelectedContentChanged()
        {
            ContentSettings settings;

            if (this.ContentSettingsList.Count <= this.SelectedContentId )
            {
                settings = new ContentSettings();
                settings.AlbumIndex = 0;
                settings.GoogleId = this.SelectedContent.Properties.GetString("GoogleId", this.globalOptions.GetString("DefaultGoogleId", ""));
                settings.SizeIndex = 9;
                this.ContentSettingsList.Add(settings);
            }
            else
            {
                settings = this.ContentSettingsList[this.SelectedContentId];
            }

            this.txtGoogleId.Text = settings.GoogleId;

            if (this.cmbGoogleAlbums.Items.Count > 0)
                this.cmbGoogleAlbums.SelectedIndex = settings.AlbumIndex;

            if (this.cmbImageSize.Items.Count > 0) //Don't do this the first time
                this.cmbImageSize.SelectedIndex = settings.SizeIndex;

           
        }

        private void cmbImageSize_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.ContentSettingsList[this.SelectedContentId].SizeIndex = this.cmbImageSize.SelectedIndex;
            this.OnContentEdited();
        }

        private void txtGoogleId_Leave(object sender, EventArgs e)
        {
            this.SelectedContent.Properties.SetString("GoogleId", this.txtGoogleId.Text);
        }

        private void cmbGoogleAlbums_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.ContentSettingsList[this.SelectedContentId].AlbumIndex = this.cmbGoogleAlbums.SelectedIndex;

            //Todo: Get Google Images here !!!
            this.lstGoogleImages.Items.Clear();

            try
            {
                List<GoogleImage> images = GoogleImage.Get(this.txtGoogleId.Text, ((GoogleAlbum)this.cmbGoogleAlbums.SelectedItem).Name);
                foreach (GoogleImage img in images)
                {
                    this.lstGoogleImages.Items.Add(img);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("The images could not be fetched.\n" + ex.Message);
            }

        }

        private void btnGetGoogleAlbums_Click(object sender, EventArgs e)
        {
            if (this.txtGoogleId.Text.IndexOf("@") >= 0)
            {
                try
                {
                    //Clear the list
                    this.cmbGoogleAlbums.Items.Clear();

                    List<GoogleAlbum> googleAlbums = GoogleImage.GetAlbums(this.txtGoogleId.Text);
                    foreach (GoogleAlbum googleAlbum in googleAlbums)
                    {
                        this.cmbGoogleAlbums.Items.Add(googleAlbum);
                    }                          
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Could not contact Google,\nPlease check your network connection.\n" + ex.Message);
                }
            }
        }

        private void lstGoogleImages_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.OnContentEdited();
        }

        private void lstGoogleImages_DrawItem(object sender, DrawItemEventArgs e)
        {
            Graphics g = e.Graphics;

            if ((e.State & DrawItemState.Selected) == DrawItemState.Selected)
            {
                using (SolidBrush brush = new SolidBrush(Color.LightBlue))
                {
                    g.FillRectangle(brush, e.Bounds);
                }
            }
            else
            {
                using (SolidBrush brush = new SolidBrush(Color.White))
                {
                    g.FillRectangle(brush, e.Bounds);
                } 
            }

            GoogleImage image = this.lstGoogleImages.Items[e.Index] as GoogleImage;

            if (image == null)
            {
                //This should never happen, but's it's here for debug purposes
                g.FillRectangle(new SolidBrush(Color.Red), new Rectangle(e.Bounds.Left + 1, e.Bounds.Top + 1, 48, 48));
            }
            else
            {
                g.DrawImage(image.Thumbnail, new Rectangle(e.Bounds.Left + 1, e.Bounds.Top + 1, 48, 48));
            }
        }

        protected override void OnContentEdited()
        {
            if (this.lstGoogleImages.SelectedItem != null)
            {
                GoogleImage selectedImage = (GoogleImage)this.lstGoogleImages.SelectedItem;
                ImageSize currentSize = (ImageSize)this.cmbImageSize.SelectedItem;
                string imageUrl = String.Format("{0}?imgmax={1}", selectedImage.Url, currentSize.Size);

                StringBuilder bodyBuilder = new StringBuilder();
                bodyBuilder.AppendFormat("<img src=\"{0}\" alternate=\"{1}\"/>", imageUrl, selectedImage.Title);
            
                this.SelectedContent.Properties.SetString("body", bodyBuilder.ToString());
            }

            base.OnContentEdited();
        }

        private void lnkBlog_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Process urlProcess = new Process();
            urlProcess.StartInfo = new ProcessStartInfo("http://www.itcrowd.be");
            urlProcess.StartInfo.UseShellExecute = true;
            urlProcess.Start();
        }

    }
}
